<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\LihuaDeliverFee;
use app\common\model\general\LihuaStore;

/**
 * 首页分类门店评价
 */
class Deliverfee extends Api
{
    protected $noNeedLogin = ['get_arrive_times', 'get_isdoor_time']; 
    protected $noNeedRight = ['*'];

     /**
     * 获取外送可送到时间
     * **/
    public function get_arrive_times()
    {
        $city_id = $this->request->request('city_id', ''); // 城市ID
        $lng = $this->request->request('lng', ''); // 经度
        $lat = $this->request->request('lat', ''); // 纬度
        // $store_id = $this->request->request('store_id', ''); // 对应门店ID
        $isdoor = $this->request->request('isdoor', 0); // 是否到店自取
        $store_id = 0;
        //获取该定位的最新对应的门店
        $store = LihuaStore::getPointStore($city_id, $lng, $lat);
        if($store['id']!=0){
            $store_id = $store['id'];
        }else{
            $this->error('所在地区暂不支持在线订餐'); 
        }

        if ( !$city_id || !$lng || !$lat || !$store_id ) $this->error('参数错误'); // 参数错误
        $citys = LihuaCity::where(['id'=> $city_id])->find();// 获取城市信息

        /**
         *   fasttime: 30 // 统一设置的最快送达时间 (新的逻辑弃用该字段)
         *   deliver_fee: "3.00" // 统一设置的配送费用
         *   time_distance: 0 // 每公里增加的配送时间
         *   price_distance: "0.00" // 每公里增加的配送费用
         *   start_distance: 0 // 起始配送计价距离
         *   start_distance_time: 0 // 起始公里内配送时间
         * **/
        //获取对应的服务门店信息
        $store = LihuaStore::getByid($store_id); //门店信息
        //获取两点之间的长度
        $distance = $this->getDistance($lng, $lat, $store['lng'], $store['lat']); //距离
        //当前时间点
        $time = date('H:i:s');
        /**
         * 获取对应的城市的配送参数
         * **/
        $deliverInfo = LihuaDeliverFee::where([ 
            'city_id' => $city_id, 
            'start_time' => ['<=', $time], 
            'end_time' => ['>=', $time],
            'status' => 1,
            'store_id' => $store_id,
        ])->find();
        /**
         * am_start am_end pm_start pm_end
         * 计算能送达的时间点
         * 每隔10分钟获取时间点
         * $default_timelist 默认的能送达的时间点
         * **/
        $default_timelist = $this->get_point_arr($citys);
        $res_timelist = [];
        foreach ($default_timelist as $k => $v) {
            $time < $v?$res_timelist[] = $v:'';
        }
        //更具当前时间获取
        $result = $this->get_price_time($res_timelist, $time, $distance, $deliverInfo, $citys, $isdoor, $city_id, $store_id);
        $this->success('ok', $result);
    }

    //获取到店自取时间
    public function get_isdoor_time()
    {
        $city_id = $this->request->post('city_id', ''); // 城市ID
        $num = $this->request->post('num', ''); // 订单金额
        if ( !$city_id || !$num ) {$this->error('参数错误');} // 参数错误

        $citys = LihuaCity::where(['id'=> $city_id])->find();// 获取城市信息
        $time_them = time();
        $door_time_them = $time_them;
        $res_time = "";
        if($num <= 10){
            $door_time_them = strtotime("+15 minutes", $time_them);
        }
        if($num > 10 && $num <= 20){
            $door_time_them = strtotime("+25 minutes", $time_them);
        }
        if($num >= 20){
            $door_time_them = strtotime("+35 minutes", $time_them);
        }
        /**
         * am_start am_end pm_start pm_end
         * 计算能送达的时间点
         * 每隔10分钟获取时间点
         * $default_timelist
         * 默认的能送达的时间点
         * **/
        $am_start_them = strtotime($citys['am_start']);
        $am_end_them = strtotime($citys['am_end']);
        $pm_start_them = strtotime($citys['pm_start']);
        $pm_end_them = strtotime($citys['pm_end']);
        if($door_time_them<$am_start_them){
            $door_time_them = $am_start_them;
        }
        if($door_time_them>$am_end_them && $door_time_them<$pm_start_them){
            $door_time_them = $pm_start_them;
        }
        if($door_time_them>$pm_end_them){
            $door_time_them = 0;
        }
        if(!!$door_time_them){
            $res_time = date('H:i', $door_time_them);
            $this->success('ok', $res_time);
        }else{
            $res_time = 0;
            $this->error('该时间段不支持到店自取');
        }
    }

    /**
     * 计算每隔时间点的配送时间和配送价格
     *  $deliverInfo
        *  id:2 //ID
        *  city_id:3 //城市ID
        *  store_id:4 //门店ID
        *  start_time:"10:00:00"//开始时间
        *  end_time:"17:30:00"//结束时间
        *  start_deliver_fee:3 //起始送餐费用
        *  start_distance:3 //起始送餐距离
        *  start_distance_time:30 //起始距离送餐时间
        *  time_distance:10 //每增加一公里所增加的时间
        *  price_distance: //每增加一公里所增加的费用
     * 
     * **/
    public function get_price_time($res_timelist, $time, $distance, $deliverInfo, $citys, $isdoor, $city_id, $store_id){
        if(!!$isdoor) {
            return [
                'timelists' => $res_timelist,
                'price' => 0,
                'distance' => $distance,
            ];
        }
        $time_lists = [];//最终能送达的时间节点
        // ******* deliverInfo
        // id: 2
        // city_id: 3
        // store_id: 18
        // start_time: "10:00:00"
        // end_time: "17:30:00"
        // start_deliver_fee: 3
        // start_distance: 3
        // start_distance_time: 30
        // status: 1

        // ******* citys
        // fasttime: 45
        // deliver_fee: "3.00"
        // time_distance: 5
        // price_distance: "0.00"
        // start_distance: 3
        // start_distance_time: 50

        // am_start:"10:40:00"
        // am_end:"13:30:00"
        // pm_start:"17:00:00"
        // pm_end:"19:15:00"
        // min_price:"25.00"
        
        if($citys['id']==3 || $citys['id']==5){
            //如果$time下单时间属于非营业时间
            if( $time < $citys['am_start'] ){ //早过起始时间
                $time = $citys['am_start'];
            }
            if( $time > $citys['am_end'] && $time < $citys['pm_start'] ){ //早过起始时间
                $time = $citys['pm_start'];
            }
        }

        if(!$deliverInfo){
            $deliverInfo = [
                'start_deliver_fee' => $citys['deliver_fee'],
                'start_distance' => $citys['start_distance'],
                'start_distance_time' => $citys['start_distance_time'],
            ];
        }
        $deliverInfo_fasttime = $deliverInfo['start_distance_time'];//送餐所需要的时间
        $arrive_price = $deliverInfo['start_deliver_fee'];//最终送餐费用
        $large_price= 0;
        //根据距离计算时间
        if( $distance > $deliverInfo['start_distance'] ){
            //超出的距离
            $large_distance = round(bcsub($distance, $deliverInfo['start_distance'], 2));
            //根据超出的距离计算需要增加的时间
            $large_time = $large_distance * $citys['time_distance'];
            //最快送达时间
            $deliverInfo_fasttime = bcadd($large_time, $deliverInfo['start_distance_time']);
            //根据超出的距离计算需要增加的费用
            $large_price = $large_distance * $citys['price_distance'];
            //最终送达的费用
            $arrive_price = bcadd($large_price, $deliverInfo['start_deliver_fee'], 2);
        }
        //能送达的最快时间点
        $fast_time = strtotime("+".$deliverInfo_fasttime." minutes", strtotime($time));
        $fast_time_string = date('H:i:s', $fast_time);
        foreach ($res_timelist as $k => $v) {
            $fast_time_string <= $v.':00'?$time_lists[] = $v:'';
        }

        //设计所有时间点的送餐费用，涉及到免费时间段
        $deliverLists = LihuaDeliverFee::where([ 
            'city_id' => $city_id, 
            'status' => 1,
            'store_id' => $store_id,
        ])->select();

        $times_price = [];
        if(count($deliverLists)>=1){
            foreach ($time_lists as $k => $v) {
                $times_price[$v] = $arrive_price;
                foreach ($deliverLists as $k2 => $v2) {
                    $v_s = $v.':00';
                    if($v_s>=$v2['start_time']&&$v_s<=$v2['end_time']){
                        $times_price[$v] = bcadd($large_price, $v2['start_deliver_fee'], 2);
                    }
                }
            }
        }else{
            foreach ($time_lists as $k => $v) {
                $times_price[$v] = $arrive_price;
            }
        }

        //如果当前时间为上午时间，则获取下午的最快送达时间
        


        return [
            'timelists' => $time_lists,
            'price' => $arrive_price,
            'distance' => $distance,
            'times_price' => [],
            'times_price' => $times_price,
        ];
    }

    //规范时间点
    public function get_point_arr($citys)
    {
        /**
         * am_start am_end pm_start pm_end
         * 计算能送达的时间点
         * 每隔10分钟获取时间点
         * $default_timelist //默认的能送达的时间点
         * **/
        $am_start_them = strtotime($citys['am_start']);
        $am_end_them = strtotime($citys['am_end']);
        $pm_start_them = strtotime($citys['pm_start']);
        $pm_end_them = strtotime($citys['pm_end']);
        $time_arr = explode(':', $citys['am_start']);
        $point_arr = ['00', '10', '20', '30', '40', '50'];
        if( $time_arr[1] > $point_arr[0] && $time_arr[1] <= $point_arr[1] ) $time_arr[1] = $point_arr[1];
        if( $time_arr[1] > $point_arr[1] && $time_arr[1] <= $point_arr[2] ) $time_arr[1] = $point_arr[2];
        if( $time_arr[1] > $point_arr[2] && $time_arr[1] <= $point_arr[3] ) $time_arr[1] = $point_arr[3];
        if( $time_arr[1] > $point_arr[3] && $time_arr[1] <= $point_arr[4] ) $time_arr[1] = $point_arr[4];
        if( $time_arr[1] > $point_arr[4] && $time_arr[1] <= $point_arr[5] ) $time_arr[1] = $point_arr[5];
        $selectedTime = $time_arr[0].':'.$time_arr[1].':'.$time_arr[2];
        $default_timelist = [];
        //计算全天的可送达时间
        for ( $i=0; $i<=1000; $i++ ){
            $addtimes = 10*$i;
            $addTimeString = strtotime("+".$addtimes." minutes", strtotime($selectedTime));
            //判断是否超过了上午的最晚送餐时间
            if( ( $addTimeString >= $am_start_them && $addTimeString <= $am_end_them ) || ( $addTimeString >= $pm_start_them && $addTimeString <= $pm_end_them ) ){
				$default_timelist[] = date('H:i', $addTimeString);
            }else if($addTimeString <= $pm_start_them && $addTimeString >= $am_end_them){
                //中午休息时间
            }else{
                break;
            }
        }
        return $default_timelist;
    }

    /**
     * 获取到店自取可自取的最快时间
     * **/
    public function get_door_time()
    {

    }

    function getDistance($lng1, $lat1, $lng2, $lat2, $unit = 2, $decimal = 2)
    {
        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI           = 3.1415926535898;
        $radLat1 = $lat1 * $PI / 180.0;
        $radLat2 = $lat2 * $PI / 180.0;
        $radLng1 = $lng1 * $PI / 180.0;
        $radLng2 = $lng2 * $PI / 180.0;
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $distance = $distance * $EARTH_RADIUS * 1000;
        if ($unit === 2) {
            $distance /= 1000;
        }
        return round($distance, $decimal);
    }


    /**
     * 获取企业私定的企业数量
     */
    public function getesnnum()
    {
        $cityname = $this->request->request('cityname');
		//使用钱包余额支付订单
		$post_data = array();
		$ret = Http::post("https://private.lihua.com/api/enterprise/getesnnumber", $post_data);
		$res = json_decode($ret, true);
		$this->success('ok', $res);
    }
    /**
     * 分类
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID：3")
     * @ApiParams   (name="store_id", type="int", required=false, description="门店ID：18")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1567675144","data":{"category_list":[{"id":202,"name":"开心饮品（满35免送餐费）","goods":[{"id":50,"category_id":202,"name":"听装雪花啤酒","short_name":"雪花","description":"常温 净含量330ml（配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2018\/11\/thumb_5bdaa5ad5df8a.jpg","original_price":0,"price":5,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0}]},{"id":57,"name":"开心加料（单点不含餐具）","goods":[{"id":43,"category_id":57,"name":"蛋花汤料","short_name":"蛋花汤","description":"含汤碗 净含量8克（配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2016\/09\/thumb_57cfc743835e0.jpg","original_price":0,"price":2,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0},{"id":46,"category_id":57,"name":"雪菜汤料","short_name":"雪菜汤","description":"含汤碗 净含量3克（配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2016\/09\/thumb_57cfc709e088f.jpg","original_price":0,"price":1,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0},{"id":44,"category_id":57,"name":"三件套","short_name":"三件套","description":"三件套（不含汤勺，配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2018\/12\/thumb_5c0f521445dd8.JPG","original_price":0,"price":2.5,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0},{"id":45,"category_id":57,"name":"米饭","short_name":"白饭","description":"套餐里已含一份米饭（配餐产品，不单独售卖）（不配套餐具）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2016\/09\/thumb_57cfc71baf78d.jpg","original_price":0,"price":3,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0}]},{"id":218,"name":"暖心砂锅","goods":[{"id":32797,"category_id":218,"name":"特别的爱砂锅","short_name":"特爱砂锅","description":"六荤六素全家福","pic":"http:\/\/image.lihua.com\/images\/newweb\/2019\/08\/thumb_5d5b494cbe158.jpg","original_price":0,"price":25,"box_fee":2,"limit_num":1,"at_least":1,"is_alone_sale":1,"enable_stock":0}]}]}})
     */
    public function category()
    {
        $city_id  = (int)$this->request->request('city_id', 0);
        $store_id = (int)$this->request->request('store_id', 0);
        if (!$city_id) $this->error('参数错误');

        $list = LihuaGoods::getCityCategoryGoodsList($city_id, $store_id);
        $this->success('OK', ['category_list' => $list]);
    }
    /**
     * 城市列表
     *
     * @ApiMethod   (POST)
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1566239128","data":{"city_list":[{"id":1,"name":"北京"},{"id":2,"name":"上海"},{"id":3,"name":"常州"},{"id":4,"name":"南京"},{"id":5,"name":"苏州"},{"id":6,"name":"无锡"},{"id":7,"name":"广州"}]}})
     */
    public function city()
    {
        $list = LihuaCity::getCityList();
        $this->success('OK', ['city_list' => $list]);
    }
    //get_city_phone 根据城市id获取该城市的客服电话
    public function get_city_phone()
    {
        $city_id = (int)$this->request->request('city_id', 0); //城市id
        $tel = LihuaCity::where('id', $city_id)->field('tel')->find();
        $this->success('OK', $tel);
    }
    /**
     * 获取当前城市企业私定的申请请求
     */
    public function private_req(){
        $phone = (int)$this->request->request('phone', 0); //联系号码
        $company = $this->request->request('company', ''); //企业名称
        $name = $this->request->request('name', ''); //客户名称
        $city_id = $this->request->request('city_id', ''); //当前城市ID
        $city_name = $this->request->request('city_name', ''); //当前城市名称
        $num = (int)$this->request->request('num', 0); //企业用餐人数
        if (!$company || !is_numeric($phone) || !$name || !$city_id || !$city_name ) {
            $this->error('参数错误');
        }
        if($num==0){
            // $this->error('请输入用餐人数');
        }
        if(strlen($company)<=3){
            $this->error('公司名称不能少于三个字符');
        }
        //一个用户只能申请三次
        $has_req = LihuaPrivateReq::where(['user_id'=> $this->auth->id])->count();
        if($has_req<3){
            $data = [
                'mobile' => $phone,
                'company' => $company,
                'consignee' => $name,
                'city_id' => $city_id,
                'city_name' => $city_name,
                'user_id' => $this->auth->id,
                'num' => $num,
            ];
            $req = LihuaPrivateReq::create($data);
            $this->success('OK', $req);
        }else{
            $this->error('一个账号只能提交三次申请');
        }
    }
    /**
     * 企业私定请求数据处理
     */
    public function private_req_do(){
        $result = $this->request->request('result', ''); //处理结果
        $id = (int)$this->request->request('id', ''); //数据id
        if (!$result ) {
            $this->error('参数错误');
        }
        $data = LihuaPrivateReq::where(['id'=> $id])->find();
        $data->status = 1;
        $data->remark = $result;
        $s = $data->save();
        $this->success('OK', $s);
    }
    //检测是否需要弹出谈框活动
    public function check_popup_isneedshow()
    {
        // LihuaMainPopup
        $mainpopup_id = $this->request->request('mainpopup_id', ''); //谈框活动id
        $uid = (int)$this->request->request('uid', ''); //用户id
        if(!$mainpopup_id || !$uid ) $this->error('参数错误');
        $mainpopup_act = LihuaMainPopup::where(['id' => $mainpopup_id])->find();//参与历史记录
        // 获取当天日期
        $today = date('Y-m-d');
        if($mainpopup_act['type']==1){
            // 登录领取红包
            $bonus_act = LihuaBonusAct::where('id', $mainpopup_act['active_id'])->find();
            // 得到活动后判断该用户是否已经参加过/如果每日可领取，则需要带上日期判断
            // mainpopup_act
            $where = ['user_id'=> $uid, 'act_id'=> $bonus_act['id']];
            if($mainpopup_act['everyday']==1){
                $where['createtime_text'] = ['like', '%'.$today.'%'];
            }
            $is_get_res = LihuaBonusActlog::where($where)->find();
            if($is_get_res){
                // 已经领取过了
                $this->error('已参加');
            }else{
                $this->success('未参加');
            }
        }
        if($mainpopup_act['type']==2){
            // 获取活动文章详情
            $article_act = LihuaArticles::where('id', $mainpopup_act['article_id'])->find();
            $active_id_arr = [];
            if($article_act['open_active_id']!='') $active_id_arr[] = $article_act['open_active_id'];
            if($article_act['share_active_id']!='') $active_id_arr[] = $article_act['share_active_id'];
            if($article_act['button_active_id']!='') {
                $active_id_arr[] = $article_act['button_active_id'];
            };
            $where = ['user_id'=> $uid, 'act_id'=>['in', $active_id_arr]];
            if($mainpopup_act['everyday']==1){
                $where['createtime_text'] = ['like', '%'.$today.'%'];
            }
            $is_get_res = LihuaBonusActlog::where($where)->find();
            if($is_get_res){
                // 已经领取过了
                $this->error('已参加');
            }else{
                $this->success('未参加');
            }
        }
    }
    // 获取首页弹屏广告列表
    public function get_main_popup(){
        $city_id = $this->request->request('city_id', 0);
        $now = time();
        $list = LihuaMainPopup::where('city_id', $city_id)
                    ->where("'{$now}' BETWEEN `starttime` AND `endtime`")
                    ->field('id,name,pic,active_id,type,city_id,createtime,article_id')
                    ->select();
        // $s = LihuaMainPopup::getLastSql();
        $data = [];
        if($list) $data = $list;
        $this->success('OK', $data);
    }
    /**
     * 门店及库存
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=false, description="城市id")
     * @ApiParams   (name="lng", type="string", required=true, description="经度：119.957481")
     * @ApiParams   (name="lat", type="string", required=true, description="纬度：31.713501")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1571296846","data":{"store":{"id":18,"name":"湖塘","city_id":3},"stocks":{"1180":5000,"2228":200}}})
     */
    public function store() {
        $city_id = $this->request->request('city_id', 0);
        $lng     = $this->request->request('lng', '');
        $lat     = $this->request->request('lat', '');
        if (!is_numeric($lng) || !is_numeric($lat)) $this->error('参数错误');

        $store = LihuaStore::getPointStore($city_id, $lng, $lat);
        $city_id = $store['city_id'];
        $data['store']  = $store;
        $data['stocks'] = null;
        $data['city_id'] = $city_id;
        $citys = LihuaCity::where('id', $city_id)->field('name')->find();
        $data['city_name'] = $citys['name'];
        if ($store['id'] > 0) {
            $goods_ids  = LihuaGoods::where(['city_id' => $city_id, 'enable_stock' => 1])->column('id');
            if (!empty($goods_ids)) {
                $data['stocks'] = LihuaStock::whereIn('goods_id', $goods_ids)
                    ->where('store_id', $store['id'])
                    ->whereNotNull('num')
                    ->column('goods_id,num');
            }
        }
        $this->success('OK', $data);
    }

    /**
     * 默认门店
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市id")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1570282516","data":{"id":25,"name":"丽华"}})
     */
    public function defstore() {
        $city_id  = $this->request->request('city_id', 0);
        if (!$city_id) $this->error('参数错误');

        $row = LihuaStore::where(['city_id' => $city_id, 'isdef' => 1])->field('id,name')->find();
        if (!$row) {
            $row = ['id' => 0, 'name' => ''];
        }
        $this->success('OK', $row);
    }
    /**
     * 评价列表
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="page", type="int", required=true, description="当前页，默认第1页")
     * @ApiParams   (name="page_size", type="int", required=false, description="每页条数，默认20条")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1571327639","data":{"page":1,"total":2,"page_size":20,"total_page":1,"list":[{"id":2,"nickname":"大帝","score":4.3,"content":"酸菜鸡真的很酸爽，吃了还想吃，赞","pics":["https:\/\/lihua.czapi.cn\/uploads\/goods\/2019\/10\/48345da884e09488c.jpg"],"time":"2019-10-14 12:31"},{"id":1,"nickname":"灰太狼","score":5,"content":"滑鸡饭分量足，真的好好吃","pics":["https:\/\/lihua.czapi.cn\/uploads\/goods\/2019\/10\/20725d9efea561b3e.jpg","https:\/\/lihua.czapi.cn\/uploads\/goods\/2019\/10\/56775da8853c519a2.jpg"],"time":"2019-10-11 19:17"}]}})
     */
    public function comment()
    {
        $city_id   = (int)$this->request->post('city_id');
        if (!$city_id) $this->error('参数错误');
        $page      = max(1, (int)$this->request->post('page'));
        $page_size = (int)$this->request->post('page_size') ? : 20;
        $data      = [
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $where = ['city_id' => $city_id, 'status' => 1];
        $total = LihuaComment::where($where)->count();
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $res = LihuaComment::where($where)
                ->field('id,nickname,content,goods_score,courier_score,service_score,pics,create_time')
                ->order('id', 'desc')->page($page, $page_size)->select();
            $list = [];
            foreach ($res as $k => $v) {
                $score  = round(($v['goods_score'] + $v['courier_score'] + $v['service_score']) / 3, 1);
                $list[] = [
                    'id' => $v['id'],
                    'nickname' => $v['nickname'],
                    'score'    => $score,
                    'content'  => htmlentities($v['content']),
                    'pics'     => explode(',', $v['pics']),
                    'time'     => date('Y-m-d H:i', $v['create_time']),
                ];
            }
            $data['list'] = $list;
        }

        $this->success('OK', $data);
    }
    /**
     * 生成现金抵用券   
     * */
    public function create_vouchers(){
        $num = 1;
        $sn = "";
        $res_arr = [];
        for( $i=0; $i<$num; $i++ ){
            $sn = strtoupper(Random::alnum(10));
            $start_t = strtotime('2023-04-02');
            $end_t = strtotime('2023-09-22');
            $data = [
                'sn' => $sn,
                'city_id' => 3,
                'start_date' => date('Y-m-d', $start_t),
                'end_date' => date('Y-m-d', $end_t),
                'status' => 0,
                'price' => 20,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $res = LihuaVouchers::insert($data);
            $res_arr[] = $res;
        }
        $this->success('OK', $res_arr);
    }
    /**
     * 测试
     * 
    */
    public function test(){
        $xml   = "msgType=wx.notify&payTime=2021-07-20+10%3A47%3A06&buyerCashPayAmt=3900&connectSys=UNIONPAY&sign=176A86ADAACEE4D1293238250BE15351A461FC2E78FB27F4FE5DC87F658ACE36&merName=%E5%B8%B8%E5%B7%9E%E4%B8%BD%E5%8D%8E%E5%BF%AB%E9%A4%90%E9%9B%86%E5%9B%A2%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&mid=898320458141154&invoiceAmount=3900&settleDate=2021-07-20&billFunds=%E7%8E%B0%E9%87%91%3A3900&buyerId=otdJ_uP74ptc4h2LjKMeUNKMnEz8&mchntUuid=2d9081bc7394a692017394cbf14d480c&tid=D0111704&instMid=MINIDEFAULT&fu=JBuj&receiptAmount=3900&couponAmount=0&targetOrderId=4200001158202107206694280741&signType=SHA256&billFundsDesc=%E7%8E%B0%E9%87%91%E6%94%AF%E4%BB%9839.00%E5%85%83%E3%80%82&subBuyerId=o_mYZ0a1E8UGPSxiEOJVNWdyX0Fc&orderDesc=%E5%B8%B8%E5%B7%9E%E4%B8%BD%E5%8D%8E%E5%BF%AB%E9%A4%90%E9%9B%86%E5%9B%A2%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&seqId=22586693540N&merOrderId=10F1_2107380732044218_1418159573&targetSys=WXPay&bankInfo=%E5%BB%BA%E8%AE%BE%E9%93%B6%E8%A1%8C%28%E5%80%9F%E8%AE%B0%E5%8D%A1%29&totalAmount=3900&createTime=2021-07-20+10%3A47%3A01&buyerPayAmount=3900&notifyId=df715982-b6f9-46c3-94c0-7e8fe6a36939&subInst=100200&status=TRADE_SUCCESS";
		$wxpay = new WxPay();
		
        $res   = $wxpay->xmlstr_to_array_unionpay($xml);
        $this->success('OK', $res);
    }
}
